import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import { Row, Col, Form, Card, Input,  Icon, Button, message, TreeSelect } from "antd";
import Upload from "../../../components/Upload";

const FormItem = Form.Item;
const { TextArea } = Input;


@connect(({ appversion }) => ({
  detaildata: appversion.detailinfo,
  loading:appversion.loading,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class NoticeAdd extends PureComponent {
  constructor(props) {
    super(props);
    this.detailInfoId = this.props.match.params.id && this.props.match.params.id!='detail' ? this.props.match.params.id : 0;
    this.state={
      fileList:[] ,
    }
  }

  componentDidMount() {

    // 编辑时 读取详情
    if (this.detailInfoId!==0) {
      this.props.dispatch({
        type: "appversion/fetch_appversion_info",
        payload: {
          id: this.detailInfoId
        }
      })
        .then(() => {
          this.setState({
            fileList: this.props.detaildata && this.props.detaildata.versionFile || []
          });
        });
    }
  }






  handleFormSubmit(e)  {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch } = this.props;
        const action = this.detailInfoId!=0 ? 'edit' : 'add';
        const id = this.detailInfoId!=0 ? this.detailInfoId : undefined;
        if(values.fileToken && values.fileToken.length>0){
          values.fileToken = values.fileToken[0]
        }
        dispatch({
          type: `appversion/${action}_appversion`,
          payload: {
            ...values,
            id
          }
        }).then(() => {
            this.handleReset();
            message.success(this.detailInfoId!=0 ? "版本信息已修改" : "版本已添加");
            if(this.detailInfoId!=0){
              this.goBack();
            }else{
              router.push({ pathname:`/system/appversion/list`});
            }
        });
      }
    });
  }

  handleReset = () => {
    this.props.form.resetFields();
  };


  goBack = () => {
    const { dispatch, location } = this.props;
    router.push({ pathname:`/system/appversion/list`,  query: { ...location.query} });
  }


  // 多文件上传
  uploadFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    const filelist =
      e &&
      e.fileList.reduce((arr, current) => {
        if (
          current.response &&
          current.response.data &&
          current.response.data.token
        ) {
          return arr.concat(current.response.data.token);
        } else {
          if (current.status && current.status === "error") {
            return arr.concat([]);
          } else {
            return arr.concat(current.uid);
          }
        }
      }, []);
    return filelist;
  };

  handleUploadFiles = info => {
    const { detailId } = this.props;
    let fileList = info.fileList;
    fileList = fileList.slice(-1);
    // if(fileList.length > 1){
    //   message.error("最多只能上传1个文件")
    //   return false
    // }

    if (info.file.status == "done") {
      //const filename_str = info.file.name.split(".");
      // this.props.form.setFieldsValue({
      //   project_name: filename_str[0]
      // });

      fileList = fileList.map(item => {
        if (item.response && item.response.error_no != "0") {
          item.status = "error";
        }
        return item;
      });
    }


    this.setState({ fileList });
  };

  handleRemoveUploadFiles = file => {};

  render() {
    const {  loading, detaildata } = this.props;
    const { getFieldDecorator } = this.props.form;

    // const detaildata = resdata.list.find(item=>item.appVersionId==this.detailInfoId);
    // console.log(detaildata)

    return (
       <Card
             bodyStyle={{padding:'50px 100px'}}
       >
            <Form layout="horizontal">
              <Row gutter={24}>
                <Col span={12}>
                  <FormItem label="版本号">
                    {getFieldDecorator("versionNum", {
                      initialValue: this.detailInfoId === 0 ? undefined : detaildata && detaildata.versionNum,
                      rules: [
                        {
                          required: true,
                          message: "请输入版本号"
                        }
                      ]
                    })(<Input placeholder="请输入版本号" />)}
                  </FormItem>
                </Col>

                <Col span={24}>
                  <FormItem label="版本描述" >
                    {getFieldDecorator("versionDesc", {
                      initialValue: this.detailInfoId === 0 ? undefined : detaildata && detaildata.versionDesc,
                      rules: [{ max: 200, message: "不超过200个字" }]
                    })(
                      <TextArea
                        placeholder="请输入版本描述"
                        autosize={{ minRows: 3, maxRows: 6 }}
                      />
                    )}
                  </FormItem>
                </Col>

                <Col span={24}>
                  <FormItem
                    label="上传文件"
                  >
                    {getFieldDecorator("fileToken", {
                      valuePropName: "file",
                      getValueFromEvent: this.uploadFile,
                    })(
                      <Upload
                        // defaultFileList={detailId === 0 ? null : detaildata.devDatum}
                        fileList={this.state.fileList}
                        onChange={this.handleUploadFiles}
                        onRemove={this.handleRemoveUploadFiles}
                      >
                        <Button>
                          <Icon type="upload" /> 上传
                        </Button>
                      </Upload>
                    )}
                  </FormItem>
                </Col>

                {/*

                <Col span={8}>
                  <FormItem label="排序">
                    {getFieldDecorator("sort", {
                      initialValue: this.detailInfoId === 0 ? 0 : detaildata && detaildata.sort,
                    })(<InputNumber placeholder="请输入" precision={0}   />)}
                  </FormItem>
                </Col>


                */}


              </Row>



              <Row gutter={24} >
                <Col span={24} style={{textAlign:'center',padding:30}}>
                    <Button
                      onClick={this.handleFormSubmit.bind(this)}
                      type="primary"
                      size="large"
                      style={{marginRight:15}}
                      loading={loading.add}
                    >
                      提交
                    </Button>
                    <Button
                      onClick={this.handleReset.bind(this)}
                      type="default"
                      size="large"
                    >
                      重置
                    </Button>
                </Col>
              </Row>
            </Form>



       </Card>
    );
  }
}
